<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="formDialogVisible = true"> 新增房间 </t-button>
        </div>
      </t-row>
      <t-table :data="data" :columns="COLUMNS" :row-key="rowKey" vertical-align="top" :hover="true"
        :pagination="pagination" :selected-row-keys="selectedRowKeys" :loading="dataLoading">
        <template #state="{ row }">
          <t-tag v-if="row.rent_mark === NUMBER_STATUS.CHECKIN" theme="danger" variant="light"> 已租 </t-tag>
          <t-tag v-if="row.rent_mark === NUMBER_STATUS.CHECKOUT" theme="success" variant="light"> 空闲 </t-tag>
        </template>
        <template #op="{ row }">
          <t-space>
            <t-link theme="primary" @click="handleEdit(row)">修改</t-link>
            <t-link theme="primary" v-if="row.rent_mark === NUMBER_STATUS.CHECKOUT"
              @click="handleCheckIn(row)">入住</t-link>
            <t-link theme="primary" v-if="row.rent_mark === NUMBER_STATUS.CHECKIN"
              @click="handleCheckOut(row)">退房</t-link>
            <t-link theme="danger" @click="handleClickDelete(row)">删除</t-link>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <t-dialog v-model:visible="deleteVisible" body="确认是否删除？" header="提示" :on-cancel="onCancel"
      @confirm="onConfirmDelete" />

    <dialog-form v-model:visible="formDialogVisible" :data="formData" @refreshData="fetchData()" />
    <check-in-form v-model:visible="checkInFormDialogVisible" :data="checkInFormData" @refreshData="fetchData()" />

    <t-dialog v-model:visible="checkOutVisible" header="退房结算" :width="680" :footer="false" :on-closed="onClickCloseBtn">
      <template #body>
        <!-- 表单内容 -->
        <!-- <t-form ref="form" :data="checkOutFormData" :rules="rules" :label-width="100" @submit="onSubmit"> -->
        <t-form ref="form" :data="checkOutFormData" :label-width="100" @submit="onSubmit">
          <t-form-item label="房间名称" name="number_name">
            <t-input v-model="checkOutFormData.number_name" :style="{ width: '480px' }" readonly />
          </t-form-item>
          <t-form-item label="退房日期" name="leave_time">
            <t-date-picker v-model="checkOutFormData.leave_time" :style="{ width: '480px' }" mode="date" clearable />
          </t-form-item>
          <t-form-item style="float: right">
            <t-button variant="outline" @click="onClickCloseBtn">取消</t-button>
            <t-button theme="primary" type="submit">确定</t-button>
          </t-form-item>
        </t-form>
      </template>
    </t-dialog>

    <t-loading :loading="loading" text="加载中..." fullscreen />
  </div>
</template>

<script lang="ts">
export default {
  name: 'HouseNumber',
};
</script>

<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { getNumber, deleteNumber, checkOut } from '@/api/house/number';
import { FormRules, MessagePlugin, SubmitContext } from 'tdesign-vue-next';

import { COLUMNS } from './constants';
import type { FormData } from './components/NumberForm.vue';
import type { CheckInData2 } from './components/CheckInForm.vue';
import DialogForm from './components/NumberForm.vue';
import CheckInForm from './components/CheckInForm.vue';
import { NUMBER_STATUS } from '@/constants';
import { constant } from 'lodash';

// 必需。table唯一标识一行数据的字段名，
const rowKey = 'id';

// 修改功能
const INITIAL_DATA: FormData = {
  id: 0,
  name: '',
  propertyID: '',
  property_name: '',
  rental: undefined,
  deposit: undefined,
  management: undefined,
  daily_rent: undefined,
  water_price: undefined,
  electricity_price: undefined
};
const formData = ref({ ...INITIAL_DATA });
const formDialogVisible = ref(false);

// 入住功能
const CHECKIN_DATA: CheckInData2 = {
  number_name: '',
  number_id: ''
};
const checkInFormData = ref({ ...CHECKIN_DATA });
const checkInFormDialogVisible = ref(false);

// 退房功能
const checkOutVisible = ref(false);
const checkOutFormData = ref({ number_name: '', id: '', leave_time: '' });

// 列表查询功能，data为列表数据
const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});
const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list } = await getNumber();
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  } finally {
    dataLoading.value = false;
  }
};
// 用于在组件挂载到 DOM 上之后执行一些操作
onMounted(() => {
  fetchData();
});

// 修改功能
const handleEdit = (row: FormData) => {
  formDialogVisible.value = true;
  formData.value = { ...row };
};

// 入住功能
const handleCheckIn = (row: any) => {
  checkInFormDialogVisible.value = true;
  // checkInFormData.value = { ...row };
  checkInFormData.value = { number_name: row.name, number_id: row.id };
};

// 退房功能
const handleCheckOut = (row: any) => {
  checkOutVisible.value = true;
  checkOutFormData.value = { number_name: row.name, id: row.id, leave_time: '' };
};

const onClickCloseBtn = () => {
  checkOutVisible.value = false;
};

const loading = ref(false);

const onSubmit = async ({ firstError }: SubmitContext<FormData>) => {
  if (!firstError) {
    try {
      loading.value = true;
      await checkOut(checkOutFormData.value);
      fetchData();
    } catch (e) {
      if (e.response && e.response.data.code === 995) {
        MessagePlugin.error(e.response.data.message);
      } else {
        MessagePlugin.error('系统错误');
      }
    } finally {
      loading.value = false;
      checkOutVisible.value = false;
    }
  } else {
    // console.log('Errors: ', validateResult);
    MessagePlugin.warning(firstError);
  }
};

// 删除功能
const deleteIdx = ref(-1);
const deleteVisible = ref(false);
const selectedRowKeys = ref([1, 2]);
const resetIdx = () => {
  deleteIdx.value = -1;
};
const handleClickDelete = (row: any) => {
  deleteVisible.value = true;
  deleteIdx.value = row.id;
};
const onConfirmDelete = async () => {
  // 真实业务请发起请求
  try {
    await deleteNumber({ id: deleteIdx.value });
    fetchData();
    resetIdx();
  } catch (e) {
    if (e.response && e.response.data.code === 995) {
      MessagePlugin.error(e.response.data.message);
    } else {
      MessagePlugin.error('系统错误');
    }
  } finally {
    deleteVisible.value = false;
  }
};
const onCancel = () => {
  resetIdx();
};
</script>

<style lang="less" scoped>
.list-card-container {
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__body) {
    padding: 0;
  }
}

.left-operation-container {
  display: flex;
  align-items: center;
  margin-bottom: var(--td-comp-margin-xxl);
}
</style>
